package mysqlConnecionMappersPackage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dataConnectionPackage.DataConnector;
import dataConnectionPackage.IMapper;
import dataTypesPackage.Musteri;

public class MusteriMapper implements IMapper{
	private ResultSet rs;
	@Override
	public Object get(int ID) {
		Musteri musteri;
		// Gets musteri with given ID
		rs = DataConnector.getInstance().query("select * from `musteri` where `musteriID` = " + ID + "");
		if (rs != null){
			
			try {
				rs.next();
				if (Integer.parseInt(rs.getString(5)) == 1 ){
					 musteri= new Musteri(Integer.parseInt(rs.getString(1)),rs.getString(2), rs.getString(3),Integer.parseInt(rs.getString(4)));
					 return musteri;
				}
				else
					System.out.println("you don't have acces to musteri with given ID");
			} catch (NumberFormatException e) {
				System.out.println("MusteriMapper: number format problem");
				e.printStackTrace();
			} catch (SQLException e) {
				System.out.println("MusteriMapper: sql problem");
				e.printStackTrace();
			}
		}
		else
			System.out.println("no musteri with given ID");
		return null;
	}

	@Override
	public int set(Object object) {
		// records given musteri, returns ID of it
        boolean isUpdated;
        Musteri musteri=(Musteri) object;
		try {
			isUpdated = DataConnector.getInstance().update("INSERT INTO `musteri` " +
//			        "(MusteriID, name, surname, musteriType) " +
//			        "values ('"+(DataConnector.getInstance().countRows("musteri")+1)+"', '"+musteri.getName()+"', '"+musteri.getSurName()+"', '"+musteri.getMusteriType().ordinal()+"')");
			        "(name, surname, musteriType) " +
			        "values ('"+musteri.getName()+"', '"+musteri.getSurName()+"', '"+musteri.getMusteriType().ordinal()+"')");
			if (isUpdated)
				return DataConnector.getInstance().countRows("musteri");
		} catch (SQLException e) {
			System.out.println("musteriMapper: sql problem");
			e.printStackTrace();
		}

		return -1;
	}
	
	@Override
	public List<Object> getAll() {
		// Gets all musteris, returns as ArrayList
		List<Object> allMusterisList = new ArrayList<Object>();
		rs = DataConnector.getInstance().query("select * from `musteri`;");
        try {
        	if (rs != null){
        		while(rs.next()){
        			int numberOfRows = DataConnector.getInstance().countRows("musteri");
        			Musteri temp;
        			for (int i=1;i<=(numberOfRows*5);i+=5){																		//table has 5 coloums. since we add 5 every loop, 5*row needed
        				temp = new Musteri(Integer.parseInt(rs.getString(i)),rs.getString(i+1), rs.getString(i+2),Integer.parseInt(rs.getString(i+3)));
        				allMusterisList.add(temp);
        			}               
        		}
        	}
        }
        catch(Exception e){
        	e.printStackTrace();
        }
		return allMusterisList;
	}
}
